import { Injectable } from '@nestjs/common';
import { CreateBoxDto } from 'src/dto/create-box.dto';
import { UpdateBoxDto } from 'src/dto/update-box.dto';
import { Box } from 'src/entity/box.entity';
import { QueryBoxDto } from 'src/dto/query-box.dto';
import { parseQueryParams } from 'src/common/utils';

@Injectable()
export class BoxService {
  create(createBoxDto: CreateBoxDto) {
    return Box.save({
      ...createBoxDto,
    });
  }

  async findAll(pageNum: number, pageSize: number) {
    const [list, count] = await Box.findAndCount({
      skip: (pageNum - 1) * pageSize,
      take: pageSize,
    });

    return { list, count };
  }

  async query(query: QueryBoxDto) {
    let qeryBuilder = Box.createQueryBuilder('box');

    let { queryClone, pageNum, pageSize } = parseQueryParams(query, [
      'warehouseId',
      'outboundplanId',
    ]);

    qeryBuilder.where(queryClone);

    // 关联查询
    if (query.warehouseId) {
      qeryBuilder
        .leftJoinAndSelect('box.warehouse', 'warehouse')
        .leftJoinAndSelect('box.mercadosku', 'mercadosku')
        .leftJoinAndSelect('box.mercadoproduct', 'mercadoproduct')
        .andWhere('warehouse.id = :warehouseId', {
          warehouseId: query.warehouseId,
        });
    } else if (query.outboundplanId) {
      qeryBuilder
        .leftJoinAndSelect('box.warehouse', 'warehouse')
        .leftJoinAndSelect('box.mercadosku', 'mercadosku')
        .leftJoinAndSelect('box.mercadoproduct', 'mercadoproduct')
        .leftJoinAndSelect('box.outboundplan', 'outboundplan')
        .andWhere('outboundplan.id = :outboundplanId', {
          outboundplanId: query.outboundplanId,
        });
    } else {
      qeryBuilder.leftJoinAndSelect('box.warehouse', 'warehouse');
      qeryBuilder.leftJoinAndSelect('box.mercadosku', 'mercadosku');
      qeryBuilder.leftJoinAndSelect('box.mercadoproduct', 'mercadoproduct');
    }

    qeryBuilder.skip((pageNum - 1) * pageSize);
    qeryBuilder.take(pageSize);

    qeryBuilder.orderBy('box.createTime', 'DESC');
    // qeryBuilder.orderBy('box.status', 'DESC');

    let [list, count] = await qeryBuilder.getManyAndCount();

    let totalBoxNum = 0;
    let totalStockNum = 0;

    for await (const item of list) {
      totalBoxNum = totalBoxNum + 1;
      totalStockNum = totalStockNum + item.boxNumber;
    }

    return { list, count, totalBoxNum, totalStockNum };
  }

  findOne(id: number) {
    return Box.findOneBy({ id });
  }

  update(id: number, updateBoxDto: UpdateBoxDto) {
    return Box.update(id, { ...updateBoxDto });
  }

  remove(id: number) {
    return Box.update(id, { deleteTime: new Date() });
  }
}
